//
//  HLRecommendViewModel.swift
//  HLXiMaLaYa
//
//  Created by hulinhu on 2018/1/24.
//  Copyright © 2018年 hulinhu. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import NSObject_Rx
import RxDataSources
import RxAlamofire


class HLRecommendViewModel: NSObject {
    
    private let vmDatas = Variable<[([HLFocusModel]?, [HLSquareModel]?, HLCategoryModel?, [HLRecommendModel]?, [HLRecommendModel])]>([])
    
    private var pageIndex: Int = 1
    
    // 网络请求类
    let provider = HLNetWorkProvider<HLRecommendNetManager>()

}

extension HLRecommendViewModel : HLViewModelType {
    
    typealias Input = HLRecommendInput
    typealias Output = HLRecommendOutput
    
    // 输入
    struct HLRecommendInput {
    }
    // 输出
    struct HLRecommendOutput : OutputRefreshProtocol {
        var refreshStatus: Variable<HLRefreshStatus>
        
        let sections : Driver<[HLRecommendSection]>
        let requestCommand = PublishSubject<Bool>()
        // 重写
        init(sections: Driver<[HLRecommendSection]>) {
            self.sections = sections
            refreshStatus = Variable<HLRefreshStatus>(.none)
        }
    }
    
    // 重写实现
    func transform(input: HLRecommendViewModel.HLRecommendInput) -> HLRecommendViewModel.HLRecommendOutput {
        let temp_sections = vmDatas.asObservable().map {(sections) -> [HLRecommendSection] in
            return sections.map({ (focusList, squareList, category, nextCategoryList, models) -> HLRecommendSection in
                return HLRecommendSection(focusList: focusList, squareList: squareList, category: category, nextCategoryList: nextCategoryList, items: models)
            })
        }.asDriver(onErrorJustReturn: [])
        
        let output = HLRecommendOutput(sections: temp_sections)
       
        output.requestCommand.subscribe(onNext: { [weak self] (isPull) in
            
            guard let `self` = self else { return }
            if isPull {
                self.pageIndex = 0; self.provider.request(.GETRecommendList).filterSuccessfulStatusCodes().mapJSON().mapObject(type: HLHomeRecommendModel.self).subscribe(onNext: { [weak self] (datas) in
                    guard let `self` = self else { return }
                    
                    guard let focusList = datas.focusList else { return }
                    guard let squareList = datas.squareList else { return }
                    guard let categoryList = datas.categoryList else { return }
                    
                    var temp_category: [HLCategoryModel] = []
                    var temp_categorySubList: [[HLRecommendModel]] = []
                    
                    // 组装数据
                    for (index, category) in categoryList.enumerated() {
                        guard index >= 2 else { // 前两个分别是
                            continue
                        }
                        guard let categorySubList = category.list, categorySubList.count > 0 else {
                            continue
                        }
                        // 猜你喜欢 精品 三列显示
                        temp_category.append(category)
                        temp_categorySubList.append(categorySubList)
                    }
                    
                    let nextCategoryList = datas.nextCategoryList
                    if (nextCategoryList != nil && datas.maxPageId > 0) {
                        //                    let category = HCCategoryModel(map: Map(mappingType: MappingType.fromJSON, JSON: ["title": "为你推荐"]))
                        //                    temp_category.append(category!)
                        //                    temp_categorySubList.append(nextCategoryList!)
                    }
                    
                  var sectionArr: [([HLFocusModel]?, [HLSquareModel]?, HLCategoryModel?,  [HLRecommendModel]?, [HLRecommendModel])] = []
                    for (index, _) in temp_category.enumerated() {
                        sectionArr.append((focusList, squareList, temp_category[index], nextCategoryList, temp_categorySubList[index]))
                    }
                    // 更新数据
                    self.vmDatas.value = sectionArr
              
                }).disposed(by: self.rx.disposeBag)
           
            }else {
                  self.pageIndex+=1;
            self.provider.request(.GETRecommendPullList(self.pageIndex)).filterSuccessfulStatusCodes().mapJSON().mapObject(type: HLHomeRecommendModel.self).subscribe(onNext: { [weak self] (datas) in
                    guard let `self` = self else { return }
                    
                    guard let focusList = datas.focusList else { return }
                    guard let squareList = datas.squareList else { return }
                    guard let categoryList = datas.categoryList else { return }
                    
                    var temp_category: [HLCategoryModel] = []
                    var temp_categorySubList: [[HLRecommendModel]] = []
                    
                    // 组装数据
                    for (index, category) in categoryList.enumerated() {
                        guard index >= 2 else { // 前两个分别是
                            continue
                        }
                        guard let categorySubList = category.list, categorySubList.count > 0 else {
                            continue
                        }
                        // 猜你喜欢 精品 三列显示
                        temp_category.append(category)
                        temp_categorySubList.append(categorySubList)
                    }
                    
                    let nextCategoryList = datas.nextCategoryList
                    
                    if (nextCategoryList != nil && datas.maxPageId > 0) {
                        //                    let category = HCCategoryModel(map: Map(mappingType: MappingType.fromJSON, JSON: ["title": "为你推荐"]))
                        //                    temp_category.append(category!)
                        //                    temp_categorySubList.append(nextCategoryList!)
                    }
                    
                    var sectionArr: [([HLFocusModel]?, [HLSquareModel]?, HLCategoryModel?,  [HLRecommendModel]?, [HLRecommendModel])] = []
                    
                    for (index, _) in temp_category.enumerated() {
                        sectionArr.append((focusList, squareList, temp_category[index], nextCategoryList, temp_categorySubList[index]))
                    }
                    // 更新数据
                    self.vmDatas.value = sectionArr
                    
                }).disposed(by: self.rx.disposeBag)
            }
            output.refreshStatus.value = .endHeaderRefresh
            output.refreshStatus.value = .endFooterRefresh
            
        }).disposed(by: rx.disposeBag)
        
        return output
    }
}

// MARK: - 结构体  数据结构
struct HLRecommendSection {
    
    var focusList: [HLFocusModel]?
    var squareList: [HLSquareModel]?
    var category: HLCategoryModel?
    var nextCategoryList: [HLRecommendModel]?
    
    var items: [Item]
}

extension HLRecommendSection: SectionModelType {
    typealias Item = HLRecommendModel
    
    init(original: HLRecommendSection, items: [HLRecommendModel]) {
        self = original
        self.items = items
    }
}
